import React, { useState, useEffect } from 'react';
import styles from './Choose.less';
import { history, Link, useModel } from 'umi'
import ProForm from '@ant-design/pro-form'
import { Card, message, Select } from 'antd';
import { serviceLogin, getService } from '@/services/login/login';
import { LeftCircleTwoTone } from '@ant-design/icons';

const { Option, OptGroup } = Select;

export default function Page() {
  // 当前账户服务商列表
  const [reslist, setreslist]: [Login.Service[], any] = useState([])
  // 下拉选择数据
  const [data, setdata] = useState<any>([])
  // 当前默认选择第一个服务商
  // 页面请求凭证
  const [web_code, setWeb_code]: [string, any] = useState("")
  // 全局用户数据
  const { initialState, setInitialState } = useModel('@@initialState');

  const myService = async (code: any) => {
    // 获取当前账户服务商列表
    const res = await getService({ web_code: code })
    if (res.code === 200) {
      if (res.data.length > 0) {
        const services: any = res.data.map((i: LoginResponse.Service, index: number) => {
          return { label: `${i.username}(${i.s_id})`, value: index, is_admin: i.is_admin }
        })
        setreslist(res.data)
        setdata(services)
      } else {
        history.push("/user/login")
        message.info("尚未注册或绑定其他服务商账户")
      }
    } else {
      history.push("/user/login")
      message.info(res.message)
    }
  }

  useEffect(() => {
    // 没有code弹出
    if (history.location.query?.web_code === undefined) {
      history.push("/user/login")
      message.error("Illegal invasion")
      return
    }
    const code = history.location.query?.web_code
    setWeb_code(code)
    myService(code)

  }, [])

  // 登陆成功设置全局用户信息 跳转后台首页
  const LoginSuccess = async () => {

    const userInfo = await initialState?.fetchUserInfo?.();
    setInitialState({ ...initialState, currentUser: userInfo })
    message.success("登陆成功！正在登入...")
    setTimeout(() => {
      history.push("/Welcome")
    }, 2000);

  }
  /**
   * 服务商登陆
   * @param values {s_id: string}
   */
  const onLogin = async (values: { s_id: number }) => {
    reslist.map(async (s: Login.Service, index: number) => {
      if (index === values.s_id) {
        const res = await serviceLogin({ web_code, u_id: s.u_id, s_id: s.s_id })
        if (res.code === 200) {
          localStorage.setItem('token', JSON.stringify(res.data))
          await LoginSuccess()
        } else {
          if (res.code === 2001) {
            history.push("/user/login")
            message.info(res.message, 5)
            return false
          }
          message.info(res.message)
        }
      }
      return null
    })
  }

  const handleChange = async () => {

  }

  return (
    <div className={styles.container}>
      <div className={styles.warp}>
        <Card
          title="服务商选择"
          size="default"
          style={{ borderRadius: 5 }}
        >
          <ProForm
            onFinish={onLogin}
            submitter={{
              render: (_, dom) => dom.pop(),
              submitButtonProps: { block: true, size: "large" },
              searchConfig: { submitText: "登 陆" }
            }}
          >
            <ProForm.Item
              name="s_id"
              rules={[
                { required: true, message: "请选择服务商登陆" }
              ]}
              initialValue={0}
            >
              <Select style={{ width: "100%" }} size="large" onChange={handleChange}>
                <OptGroup key="1" label="主账号">
                  {data.map((item: any, index: number) => {
                    if (item.is_admin) {
                      return <Option key={index.toString()} value={item.value}>{item.label}</Option>
                    }
                    return null
                  })}
                </OptGroup>
                <OptGroup key="3" label="子账户">
                  {data.map((item: any, index: number) => {
                    if (!item.is_admin) {
                      return <Option key={index.toString()} value={item.value}>{item.label}</Option>
                    }
                    return null
                  })}
                </OptGroup>
              </Select>
            </ProForm.Item>
          </ProForm>
          <div className={styles.link}>
            <Link to="/user/login"><LeftCircleTwoTone /> 切换其他账户登陆</Link>
          </div>
        </Card>
      </div>
    </div>
  );
}
